"""
账单管理系统
"""
from datetime import datetime
from typing import Dict, List
from .models import RoomState, BillingDetail


class BillingManager:
    """账单管理器"""
    
    @staticmethod
    def generate_bill(room_state: RoomState) -> dict:
        """生成账单
        
        Args:
            room_state: 房间状态
            
        Returns:
            账单字典
        """
        return {
            'room_id': room_state.room_id,
            'check_in_time': room_state.check_in_time.strftime('%Y-%m-%d %H:%M:%S') if room_state.check_in_time else None,
            'check_out_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'total_power_consumption': round(room_state.total_power, 3),
            'total_cost': round(room_state.total_cost, 2),
            'detail_count': len(room_state.billing_details)
        }
    
    @staticmethod
    def generate_detail_list(room_state: RoomState) -> List[dict]:
        """生成详单列表
        
        Args:
            room_state: 房间状态
            
        Returns:
            详单列表
        """
        details = []
        for idx, detail in enumerate(room_state.billing_details, 1):
            details.append({
                'serial_number': idx,
                'room_id': detail.room_id,
                'start_time': detail.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                'end_time': detail.end_time.strftime('%Y-%m-%d %H:%M:%S'),
                'wind_speed': detail.wind_speed,
                'start_temp': round(detail.start_temp, 2),
                'end_temp': round(detail.end_temp, 2),
                'target_temp': round(detail.target_temp, 2),
                'duration_minutes': round(detail.duration_minutes, 2),
                'power_consumption': round(detail.power_consumption, 3),
                'cost': round(detail.cost, 2)
            })
        return details
    
    @staticmethod
    def format_bill_text(bill: dict, details: List[dict]) -> str:
        """格式化账单为文本
        
        Args:
            bill: 账单字典
            details: 详单列表
            
        Returns:
            格式化的账单文本
        """
        lines = []
        lines.append("=" * 60)
        lines.append("酒店空调使用账单".center(56))
        lines.append("=" * 60)
        lines.append(f"房间号: {bill['room_id']}")
        lines.append(f"入住时间: {bill['check_in_time']}")
        lines.append(f"退房时间: {bill['check_out_time']}")
        lines.append("-" * 60)
        lines.append(f"总耗电量: {bill['total_power_consumption']} 度")
        lines.append(f"总费用: ¥{bill['total_cost']:.2f} 元")
        lines.append("-" * 60)
        lines.append("\n详单列表:")
        lines.append("-" * 60)
        
        if details:
            # 表头
            lines.append(f"{'序号':<6}{'开始时间':<20}{'结束时间':<20}{'风速':<8}{'时长(分)':<10}{'费用(元)':<10}")
            lines.append("-" * 60)
            
            # 详单内容
            for detail in details:
                lines.append(
                    f"{detail['serial_number']:<6}"
                    f"{detail['start_time']:<20}"
                    f"{detail['end_time']:<20}"
                    f"{detail['wind_speed']:<8}"
                    f"{detail['duration_minutes']:<10.2f}"
                    f"{detail['cost']:<10.2f}"
                )
        else:
            lines.append("（无使用记录）")
        
        lines.append("=" * 60)
        
        return "\n".join(lines)
    
    @staticmethod
    def export_bill_to_file(room_state: RoomState, filename: str = None) -> str:
        """导出账单到文件
        
        Args:
            room_state: 房间状态
            filename: 文件名（可选）
            
        Returns:
            文件路径
        """
        if filename is None:
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f"bill_{room_state.room_id}_{timestamp}.txt"
        
        bill = BillingManager.generate_bill(room_state)
        details = BillingManager.generate_detail_list(room_state)
        text = BillingManager.format_bill_text(bill, details)
        
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(text)
        
        return filename

